<?php

namespace App\Http\Resources\Train\TrainOrder;

use App\Trip\Enums\TripTypes;
use App\Trip\IdentityCode\IdentityCode;
use App\Trip\Orders\TripOrderStateDesc;
use App\Trip\Passengers\OrderSubPassenger;
use App\Trip\Train\Seat\TrainPassengerSeat;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use JsonSerializable;

class TrainOrderPassengerResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     *
     * @return array|Arrayable|JsonSerializable
     */
    public function toArray($request)
    {

        $passenger = parent::toArray($request);
        if ($request->offsetGet('business') == 'train_order_list') {
            return [
                'truename'       => $passenger['truename'],
                'passenger_type' => $passenger['passenger_type'],
            ];
        }
        $is_change_passenger           = $request->offsetGet('change_passenger') == 1;
        $request_passenger_id          = $request->input('passenger_id');
        $passenger['selected_seat']    = json_decode($passenger['selected_seat'] ?? "", true);
        $passenger['order_state_desc'] = TripOrderStateDesc::transPassengerDescByOrderState(TripTypes::TRAIN, $passenger['order_state']);
        $passenger['passenger_id']     = OrderSubPassenger::buildSubPassengerId(
            $passenger['passenger_id'],
            $passenger['sequence']
        );

        // 遮挡身份证
        if (isset($passenger['identity_code'])) {
            $passenger['identity_code'] = (new IdentityCode($passenger['identity_code']))->hide();
        }
        $passenger['seat_no_desc'] = $passenger['seat_no'] ?? '';
        $passenger['seat_no']      = TrainPassengerSeat::seatNoDesc($passenger);
        if ($is_change_passenger) {
            $passenger['selected'] = $request_passenger_id == $passenger['passenger_id'];
            unset(
                $passenger['service_fee'],
                $passenger['seat_name'],
                $passenger['seat_name_uy'],
                $passenger['select_carriage'],
                $passenger['carriage'],
            );
        }
        unset(
            $passenger['created_at'], $passenger['updated_at'],
            $passenger['id'], $passenger['user_id'],
            $passenger['order_sn']
        );
        return $passenger;
    }
}
